
#引入包
import requests
from geopy.geocoders import Nominatim
geolocator = Nominatim()


#测试地址
pos = ["广东省广州市番禺区东艺路",
       "广州市石槎路神明国际380号十一区之2栋",
       "乌鲁木齐市国际大巴扎",
       "乌鲁木齐市红柳庄园",
       "北京市三里屯",
       "上海市外滩"]

#测试坐标
lonlat = ["87.6042025406,43.8213746689",
          "87.5819445623,43.8284818734",
          "87.6081735376,43.8555886719",
          "87.5648236200,43.8630123784",
          "87.6179284061,43.8772984597",
          ]


#使用高德API
#   地理编码：地址转坐标
def geocodeAmap(address):
    par = {'address': address, 'key': 'aa50c31c7450d811578ccd38cffe1ea23'}#请自备ak
    base = 'http://restapi.amap.com/v3/geocode/geo'
    response = requests.get(base, par)
    answer = response.json()
    GPS = answer['geocodes'][0]['location'].split(",")
    return GPS[0],GPS[1]
#   逆向地理编码：坐标转地址
def reGeocodeAmap(lonlat):
    if float(lonlat.split(",")[0]) < float(lonlat.split(",")[1]):
        lonlat = (lonlat.split(",")[1]) + "," + (lonlat.split(",")[0])
    par = {'location': lonlat, 'key': 'aa50c31c7450d811578ccd38cffe1ea23'}#请自备ak
    base = 'http://restapi.amap.com/v3/geocode/regeo'
    response = requests.get(base, par)
    answer = response.json()
    answer = answer["regeocode"]["formatted_address"]
    return answer

#使用百度API
#   地理编码：地址转坐标
def geocodeBaidu(address):
    base = url = "http://api.map.baidu.com/geocoder?address=" + address + "&output=json&key=aC0a72f0c67c05811883621bf439cd687"#请自备ak
    response = requests.get(base)
    answer = response.json()
    return answer['result']['location']['lng'],answer['result']['location']['lat']
#   逆向地理编码：坐标转地址
def reGeocodeBaidu(latlon):
    if float(latlon.split(",")[0]) > float(latlon.split(",")[1]):
        latlon = (latlon.split(",")[1]) + "," + (latlon.split(",")[0])
    base = url = "http://api.map.baidu.com/geocoder?callback=renderReverse&location="+ latlon +"&output=json&ak=aC0a72f0c67c05811883621bf439cd687"#请自备ak
    response = requests.get(base)
    answer = response.json()
    return answer['result']['formatted_address']

#使用OSM API
#   地理编码：地址转坐标
def geocodeOSM(i):
    location = geolocator.geocode(i)
    print (location)

#   反向地理编码：坐标转地址
def reGeocodeOSM(i):
    location = geolocator.reverse(i)
    print (location.address)

seclc = {
        "1":["高德地理编码","pos","geocodeAmap"],
        "2":["高德反向地理编码","lonlat","reGeocodeAmap"],
        "3":["百度地理编码","pos","geocodeBaidu"],
        "4":["百度反向地理编码","lonlat","reGeocodeBaidu"],
        "5":["OSM 地理编码","pos","geocodeOSM"],
        "6":["OSM 反向地理编码","reGeocodeOSM"]
        }

print (
        " ===================\n",
        "1. 高德地理编码\n",
        "2. 高德反向地理编码\n",
        "3. 百度地理编码\n",
        "4. 百度反向地理编码\n",
        "5. OSM 地理编码\n",
        "6. OSM 反向地理编码\n",
        "===================\n",
        )

type = input("请选择测试的序号：\n")

for i in eval(seclc[str(type)][1]):
    print (seclc[str(type)][0],"：",i)
    print (eval(seclc[str(type)][2])(i),"\n")


